package com.mall.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mall.db.domain.Category;

import java.util.List;

public class CategoryJson {
    public static String getCategoryTree(List<Category> list){
        JSONArray ja  = new JSONArray();

        JSONArray array = JSONArray.parseArray(JSON.toJSONString(list));

        JSONObject all = new JSONObject();

        //把list转换为map(JSONObject)
        for (int i=0;i<array.size();i++) {
            JSONObject json = (JSONObject)(array.get(i));
            //添加到 all 对象 类似于map
            all.put(json.getString("id"),json);

        }

        //遍历List集合
        for (int i=0;i<array.size();i++) {
            JSONObject json = (JSONObject)(array.get(i));
            //获取pid
            String pid = json.getString("pid");
            //获取pid作为key的对象
            JSONObject jo = (JSONObject) all.get(pid);
            if(jo==null){//表示json没有父元素
                ja.add(json);
            }else{
                if(jo.get("children")!=null){
                    JSONArray ch = (JSONArray)jo.get("children");
                    ch.add(json);
                    jo.put("children", ch);
                }else {
                    JSONArray ch = new JSONArray();
                    ch.add(json);
                    jo.put("children", ch);
                }
            }
        }

        return ja.toJSONString();
    }
}
